// pages/user/myCollection/myCollection.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        page: 1,
        hasMore: true,
        data: [],
        type: '10'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.type) {
            this.data.type = options.type;
        }
        this.onPullDownRefresh();
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        this.loadData(1).finally(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        if (!this.data.hasMore) return;

        const page = this.data.page + 1;
        this.loadData(page);
    },

    // 导航栏切换
    onNavTab: function(e) {
        const dataset = e.currentTarget.dataset;
        const type = dataset.type;

        this.data.type = type;
        this.setData({
            type: type
        });
        this.loadData(1);
    },

    // 取消收藏
    cancel: function(e) {
        const dataset = e.currentTarget.dataset;
        const index = dataset.index;
        const type = this.data.type;
        const item = this.data.data[index];
        const key = {
            '10': 'goods_id',
            '20': 'curriculum_id'
        }[type];

        wx.http.post('api/user.collection/delete', {
            type: type,
            goods_id: item[key]
        }, {
            showLoading: true
        }).then(() => {
            this.data.data.splice(index, 1);
            this.setData({
                data: this.data.data
            });
        });
    },

    // 加载数据列表
    loadData: function(page) {
        return wx.http.post('api/user.collection/index', {
            page: page,
            type: this.data.type,
        }).then((res) => {
            res = res.data.data.list;
            const hasMore = res.data.length >= res.per_page;
            const data = page > 1 ? this.data.data.concat(res.data) : res.data;
            this.setData({
                page: page,
                hasMore: hasMore,
                data: data,
            });
            return res.data;
        }, (err) => {
            console.warn("api/user.collection/index", err)
        });
    },

    // 取消收藏
    cancelCollectionTap: function() {
        // todo
        const index = e.currentTarget.dataset.index;
        const item = this.data.data[index];
        return wx.http.post('api/user.collection/delete', {
            goods_id: item.goods_id,
            type: this.data.type,
        }).then((res) => {
            this.setData({
                data: this.data.data.splice(index, 1)
            });
        });
    }

});